﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Caching;
using System.Web.Hosting;
using JXT.PrimaryKey.Batman.Cache;

namespace JXT.PrimaryKey.Batman.Core.Cache
{
    /// <summary>
    /// 默认的HTTP缓存
    /// </summary>
    public class HttpCache : CacheBase, ICache
    {
        private static readonly System.Web.Caching.Cache _cache = HostingEnvironment.Cache; //WEB缓存对象
        private static readonly string _namespaceFormat = "{0}.{1}"; //命名格式

        private string buildCacheKey(string ns, string key)
        {
            return String.Format(_namespaceFormat, ns, key);
        }

        public override void Add(string ns, string key, object value, TimeSpan ts)
        {
            string realKey = buildCacheKey(ns, key);
            _cache.Insert(realKey, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, ts, CacheItemPriority.Default, null);
        }

        public override object Get(string ns, string key)
        {
            string realKey = buildCacheKey(ns, key);
            return _cache.Get(realKey);
        }

        public override bool Exists(string ns, string key)
        {
            string realKey = buildCacheKey(ns, key);
            return Get(realKey) != null;
        }

        public override void Remove(string ns, string key)
        {
            string realKey = buildCacheKey(ns, key);
            _cache.Remove(realKey);
        }

        public override void Clear(string ns)
        {
            var keys = getCacheKeys(ns);
            foreach (var item in keys)
            {
                _cache.Remove(item);
            }
        }

        public override void Clear()
        {
            var keys = getCacheKeys();
            foreach (var item in keys)
            {
                _cache.Remove(item);
            }
        }

        private IEnumerable<string> getCacheKeys()
        {
            List<string> keys = new List<string>();
            foreach (IDictionaryEnumerator item in _cache)
            {
                keys.Add(Convert.ToString(item.Key));
            }
            return keys;
        }

        /// <summary>
        /// 单独实现，提高效率
        /// </summary>
        /// <param name="ns">命名空间</param>
        /// <returns>key集合</returns>
        private IEnumerable<string> getCacheKeys(string ns)
        {
            List<string> keys = new List<string>();
            foreach (IDictionaryEnumerator item in _cache)
            {
                string key = Convert.ToString(item.Key);
                if (key.StartsWith(ns))
                {
                    keys.Add(key);
                }
            }
            return keys;
        }
    }
}
